package com.ecoolex.discount.sales.core.service;

import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecoolex.admin.system.core.manager.AdminSystemConfigManager;
import com.ecoolex.admin.system.entity.AdminSystemConfig;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;

@Service
public class AdminSystemConfigInnerService {

	private AtomicBoolean inited = new AtomicBoolean(false);

	private LoadingCache<String, String> loadingCache;

	@Autowired
	AdminSystemConfigManager adminSystemConfigManager;

	public void init() {
		if (!inited.get() || Objects.isNull(loadingCache)) {
			loadingCache = Caffeine.<String, String> newBuilder().expireAfterWrite(Duration.ofMinutes(5))
					.refreshAfterWrite(Duration.ofMinutes(1)).build(key -> {
						AdminSystemConfig config = adminSystemConfigManager.getByKey(key);
						if (Objects.nonNull(config)) {
							return config.getConfigValue();
						}
						return null;
					});
			inited.set(true);

		}
	}

	public String getByKey(String key) {
		init();
		return loadingCache.get(key);
	}
}
